<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <link rel="shortcut icon" href="favicon.ico" type="image/x-icon"/>
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>transmit验证</title>
    <style>
        .container {
            max-width: 800px;
            margin: 2rem auto;
            padding: 20px;
        }

        /* 输入框组样式‌:ml-citation{ref="1" data="citationList"} */
        .input-group {
            display: flex;
            gap: 12px;
            margin-bottom: 24px;
        }


        .confirmBtn {
            padding: 12px 32px;
            background: #2196F3;
            color: white;
            border: none;
            border-radius: 6px;
            cursor: pointer;
            transition: background 0.3s;
        }

        #confirmBtn:hover {
            background: #1976D2;
        }

        .loadc{
            padding: 20px 0;
        }
        .fileSelect{
            padding: 10px 5px;
            height: 40px;
            width: 100px;
            font-size: 14px;
        }


        .error-msg {
            color: #d32f2f;
            padding: 16px;
            background: #ffebee;
            border-radius: 4px;
        }

        /* 新增表格样式 */
        table {
            width: 100%;
            border-collapse: collapse;
            margin-top: 20px;
        }

        th, td {
            border: 1px solid #ddd;
            padding: 8px;
            text-align: left;
        }

        th {
            width: 200px;
            background-color: #f2f2f2;
            font-weight: bold;
        }

        /*tr:nth-child(even) {*/
        /*    background-color: #f9f9f9;*/
        /*}*/

        tr:hover {
            background-color: #f1f1f1;
        }
        .container1 {
            display: flex;
            gap: 10px; /* 可选：设置元素之间的间距 */
        }
        .text-box, .input-box {
            padding: 10px;
            border: 1px solid #ccc;
            border-radius: 4px;
        }



        .text-box {
            width: 400px; /* 可选：设置最小宽度 */
            height: 500px;
        }

        .input-box {

            width: 400px; /* 输入框固定宽度 */
            height: 500px;
        }

    </style>
</head>
<body>
    <div class="container">
        <div class="input-group">
            <select id="http1" name="http1">
                <option value="http://" selected>HTTP</option>
                <option value="https://">HTTPS</option>
            </select>
            <input type="text" id="ipInput" value="127.0.0.1">
            <div id="p1">:</div>
            <input type="text" id="portInput" value="1880">
            <input type="text" id="pathInput" value="/windhptransmit">
            <button id="confirmBtn" class = "confirmBtn">验证transmit状态</button>
        </div>
        <div id="resultContainer"></div>
        <div>
            <table>
                <tr>
                    <th>前置机IP</th>
                    <td id = 'ip1'></td>
                </tr>
                <!-- 示例数据 -->
                <tr>
                    <th>前置机端口</td>
                    <td id = 'port1'></td>
                </tr>
                <tr>
                    <th>部署路径</td>
                    <td id = 'path1'></td>
                </tr>
            </table>
        </div>
        <div class="loadc">
            <select id="fileSelect" class="fileSelect">
                <option value="api.json">api.json</option>
                <option value="key.json">key.json</option>
                <option value="region.json">region.json</option>
                <option value="odin.json">odin.json</option>
            </select>
            <button class="confirmBtn" onclick="loadData()">加载配置文件数据</button>
            <button class="confirmBtn" onclick="updateData()">更新配置文件数据</button>
            <div id="updateRes"></div>
        </div>

        <div class="container1">
            <div id ="cacheData" class="text-box"></div>
            <div>
                <textarea id= "updateData1" style="vertical-align:middle" class= "input-box" type="text" placeholder="更新内容"></textarea>
            </div>
        </div>

    </div>

    <script>
        let url = "http://127.0.0.1:1234";
        // DOM元素引用‌:ml-citation{ref="3" data="citationList"}
        const http1 = document.getElementById('http1');
        const ipInput = document.getElementById('ipInput');
        const portInput = document.getElementById('portInput');
        const pathInput = document.getElementById('pathInput');
        const confirmBtn = document.getElementById('confirmBtn');
        const resultContainer = document.getElementById('resultContainer');
        const ip1 = document.getElementById("ip1");
        const port1 = document.getElementById("port1");
        const path1 = document.getElementById("path1");
        const updateRes = document.getElementById('updateRes');
        // 事件绑定‌:ml-citation{ref="3,4" data="citationList"}

        confirmBtn.addEventListener('click', handleRequest);


        // 核心请求逻辑‌:ml-citation{ref="3,5" data="citationList"}
        async function handleRequest() {
            const inputUrl = http1.value + ipInput.value.trim() + ":" + portInput.value.trim() + pathInput.value.trim() + "/hello";
            console.log(inputUrl)
            if (!validateUrl(inputUrl)) {
                showError('请输入有效的HTTP地址');
                return;
            }
            const fake_data = {
                "hostIp": "",
                "port": "",
                "classPath": ""
            }
            try {
                let hello_url = "/ts/hello?url="+inputUrl;
                const response = await fetch(hello_url);
                if (!response.ok) throw new Error(`HTTP错误 ${response.status}`);

                const { code, data } = await response.json();
                if (code !== 0) {
                    renderResult(fake_data);
                }else {
                    resultContainer.innerHTML = '';
                    renderResult(data);
                };

            } catch (error) {
                renderResult(fake_data);
                showError(`数据获取失败: ${error.message}`);
            }
        }

        // URL验证‌:ml-citation{ref="4" data="citationList"}
        function validateUrl(url) {
            const pattern = /^(https?):\/\/[^\s/$.?#].[^\s]*$/i;
            return pattern.test(url);
        }

        // 渲染结果‌:ml-citation{ref="1,5" data="citationList"}
        function renderResult(data) {
            ip1.innerText = data.hostIp,
            port1.innerText = data.port,
            path1.innerText = data.classPath
        }

        // 错误提示‌:ml-citation{ref="3" data="citationList"}
        function showError(message) {
            resultContainer.innerHTML = `
                <div class="error-msg">${message}</div>
            `;
        }
        async function loadData() {
            const inputUrl = http1.value + ipInput.value.trim() + ":" + portInput.value.trim() + pathInput.value.trim() + "/json/cache?fileName=";
            const fileType = document.getElementById('fileSelect').value;
            const url1 = inputUrl + fileType;
            const cacheBox = document.getElementById('cacheData');

            let json_cache = "/ts/json/cache?url="+url1;
            fetch(json_cache)
                .then(response => response.status === 200 ? response.json(): Promise.reject())
                .then(cacheData => {
                if (cacheData.code === 0) {
                    const cacheStr = JSON.stringify(cacheData.data, null, 2);
                    cacheBox.innerHTML = cacheStr;

                }else {
                    cacheBox.innerHTML = cacheData.msg;
                }
            }).catch( error => {
                cacheBox.innerHTML = "服务暂时不支持在线获取配置文件";
            })
        }
        //更新配置文件信息
        let isUpdateInProgress = false;

        function updateData() {
            if (isUpdateInProgress) {
                alert("请勿频繁点击，5秒后再试！")
                return;
            }

            if (!confirm('确定要更新配置文件数据吗？')) {
                return;
            }
            const updateDate1 = document.getElementById("updateData1").value.trim();
            if (typeof updateDate1 === 'undefined' || updateDate1 === null) {
                alert('更新内容为空。更新失败');
                return;
            }

            if (!isJSON(updateDate1)) {
                alert('更新内容不是标准json! 更新失败!');
                return;
            }
            isUpdateInProgress = true;

            const fileType = document.getElementById('fileSelect').value;
            const tturl = http1.value + ipInput.value.trim() + ":" + portInput.value.trim() + pathInput.value.trim();

            const newData1 = {
                "url" : tturl,
                "fileName" : fileType,
                "content" : JSON.parse(updateDate1)
            }
            let json_update = "/ts/json/update";
            fetch(json_update, {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json'
                },
                body: JSON.stringify(newData1) // 修改: 将 newData1 对象转换为 JSON 字符串
            })
            .then(response => response.json())
            .then(data123 => {
                    if (data123.code === 0) {
                        alert('配置文件更新成功');
                        document.getElementById('cacheData').innerText = JSON.stringify(newData1.content);
                        updateRes.innerHTML = '';
                    } else {
                        updateError(fileType);
                        alert("配置文件更新失败");
                    }
                })
            .catch(error => {
                console.error('update err:', error);
                alert('服务暂时不支持在线更新配置文件');
            }).finally(() => {
                setTimeout(() => {
                    isUpdateInProgress = false;
                }, 5000);
            });
        }
        function updateError(message) {
            updateRes.innerHTML = `
                <div class="error-msg">${message} 配置文件更新失败</div>
            `;
        }
        function isJSON(str) {
            try {
                const obj = JSON.parse(str);
                if (obj && typeof obj === "object") {
                    return true;
                }
            } catch (e) {
                // 如果发生错误，则不是有效的JSON
            }
            return false;
        }
    </script>
</body>
</html>